﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace InhollandAir.auxiliary
{
    public class Logging
    {
        private static readonly SqlConnection Conn = new SqlConnection();

        public static string LogEvent(int uid, Uri page, string action, string message, bool iserror)
        {
            string success;
            try
            {
                // Set correct connection string
                Conn.ConnectionString = ConfigurationManager.ConnectionStrings["LogAndException"].ConnectionString;

                // Check if connection is closed before trying to open
                if (Conn.State != ConnectionState.Closed) Conn.Close();

                // Open connection
                Conn.Open();

                // Set query
                const string query = "INSERT INTO [InhollandAir].[dbo].[Log] VALUES (@user_id, @page, @action, @message, @iserror, @timestamp)";

                // Create sqlcommand
                var cmd = new SqlCommand(query, Conn);

                // Add parameters
                cmd.Parameters.AddWithValue("@user_id", uid);
                cmd.Parameters.AddWithValue("@page", page.ToString());
                cmd.Parameters.AddWithValue("@action", action);
                cmd.Parameters.AddWithValue("@message", message);
                cmd.Parameters.AddWithValue("@iserror", iserror);
                cmd.Parameters.AddWithValue("@timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                // Check if more than 0 rows are created
                success = cmd.ExecuteNonQuery() > 0 ? "true" : "false";
            }
            catch(SqlException ex)
            {
                success = ex.Message + ex.InnerException;
            }
            catch (Exception ex)
            {
                // Set success to false if exception occurs
                success = ex.Message + ex.StackTrace;
            }
            finally
            {
                // Close connection now
                Conn.Close();
            }
            
            // Return success or failure
            return success;
        }

    }
}